package study.itwill.team5.exchange;

import java.io.IOException;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import study.itwill.common.NXmlParser;

public class ExchangeRate {
	public static int COUNT = 0;
	public static String DATETIME = null;
	
	public static ArrayList<ExchangeRateItem> getList() {
		ArrayList<ExchangeRateItem> list = null;
		/*
		 * <hname>미국</hname>
<standard>1140.00</standard>
<buy>1159.95</buy>
<sell>1120.05</sell>
<send>1151.10</send>
<receive>1128.90</receive>
<sign>USD</sign>
<change_val>-6.00</change_val>
		 */
		
		XmlPullParser parser = NXmlParser.getInstance().getParser("http://www.naver.com/include/timesquare/widget/exchange.xml");
		
		if (parser == null) {
			return null;
		}
		
		String hname = null;
		double standard = 0.0d;
		double buy = 0.0d;
		double sell = 0.0d;
		double send = 0.0d;
		double receive = 0.0d;
		String sign = null;
		double changeVal = 0.0d;
		
		String tag = null;
		
		try {
			list = new ArrayList<ExchangeRateItem>();
			
			int type = parser.getEventType();
			
			while (type != XmlPullParser.END_DOCUMENT) {
				tag = parser.getName();
				
				switch (type) {
				case XmlPullParser.START_TAG:
					if (tag.equals("hname")) {
						parser.next();
						hname = parser.getText();
					} else if (tag.equals("standard")) {
						parser.next();
						standard = Double.parseDouble(parser.getText());
					} else if (tag.equals("buy")) {
						parser.next();
						buy = Double.parseDouble(parser.getText());
					} else if (tag.equals("sell")) {
						parser.next();
						sell = Double.parseDouble(parser.getText());
					} else if (tag.equals("send")) {
						parser.next();
						send = Double.parseDouble(parser.getText());
					} else if (tag.equals("receive")) {
						parser.next();
						receive = Double.parseDouble(parser.getText());
					} else if (tag.equals("sign")) {
						parser.next();
						sign = parser.getText();
					} else if (tag.equals("change_val")) {
						parser.next();
						changeVal = Double.parseDouble(parser.getText());
					}
					break;
				case XmlPullParser.END_TAG:
					
					if(tag.equals("currency")) {
						ExchangeRateItem item = new ExchangeRateItem(hname, standard, buy, sell, send, receive, sign, changeVal);
						list.add(item);
					}
					
					break;
				}
				
				type = parser.next();
			}
			
		} catch (XmlPullParserException e) {
			System.out.println("파서 생성 실패 >> " + e.toString());
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("파서 읽기 실패 >> " + e.toString());
			e.printStackTrace();
		}
		return list;
	}
}
